package indi.gtl.superbrain.tools;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.conn.util.InetAddressUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by admin1 on 15-5-27.
 */
public class NetToolService {
    private static final String TAG = "NetToolService";

    public static final String CONNECTION_MSG_SERVICE_SUCCESS = "success";
    public static final String CONNECTION_MSG_SERVICE_CONNECT = "connect";

    // 向Handler中传递消息的类型
    // 被搜索
    public static final int HANDLER_MSG_SCAN = 0x11;
    // 连接成功
    public static final int HANDLER_MSG_CONNECT = 0x22;

    private Handler mHandler;
    private boolean isConnected = false;
    private OnConnectClientListener mOnConnectClientListener;

    private final String mMsg;

    /* 构造函数
    *
    *
     */
    public NetToolService(String msg){
        mMsg = msg;
        mHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case NetToolService.HANDLER_MSG_SCAN:// 被扫描到
                        break;
                    case NetToolService.HANDLER_MSG_CONNECT://被连接
                        if(mOnConnectClientListener != null)
                            mOnConnectClientListener.onConnectClient((NetTool) msg.obj);
                        break;
                }
            }
        };
    }

    public void setOnConnectClientListener(OnConnectClientListener onConnectClientListener){
        mOnConnectClientListener = onConnectClientListener;
    }

    public interface OnConnectClientListener{
        void onConnectClient(NetTool netTool);
    }

    /* 启动服务端,等待客户端的连接
    *
    *  连接成功会向Handler发送一个NetTool可用于接收和发送消息
     */
    public void startService(){
        new Thread(){
            @Override
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(NetTool.SERVERPORT);
                    while(! isConnected) {
                        Log.d(TAG, "启动服务");
                        Log.d(TAG, "本机ip:" + getLocAddress());
                        Socket socket = serverSocket.accept();
                        BufferedReader bs = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String info = bs.readLine();
                        String[] msg = info.split(NetTool.CONNECTION_MSG_SEPARATOR);
                        Log.d(TAG, "接收到消息:" + info);
                        if (msg[0].equals(NetToolClient.CONNECTION_MSG_CLIENT_SCAN)){
                                OutputStream os = socket.getOutputStream();
                                Message.obtain(mHandler, HANDLER_MSG_SCAN);
                                os.write((CONNECTION_MSG_SERVICE_SUCCESS + NetTool.CONNECTION_MSG_SEPARATOR + getLocAddress() +
                                        NetTool.CONNECTION_MSG_SEPARATOR + mMsg +
                                        NetTool.CONNECTION_MSG_END).getBytes("utf-8"));
                                os.close();
                        }else if(msg[0].equals(NetToolClient.CONNECTION_MSG_CLIENT_CONNECT)){
                                String ip = msg[1];
                                Message.obtain(mHandler, HANDLER_MSG_CONNECT, NetTool.createNetTool(ip, socket)).sendToTarget();
                                OutputStream os = socket.getOutputStream();
                                os.write((CONNECTION_MSG_SERVICE_CONNECT + NetTool.CONNECTION_MSG_SEPARATOR + getLocAddress() + NetTool.CONNECTION_MSG_END).getBytes("utf-8"));
                                return;
                        }

                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public String getLocAddress(){
        String ipaddress = "";
        try {
            Enumeration en = NetworkInterface.getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements()) {
                NetworkInterface networks = (NetworkInterface) en.nextElement();
                // 得到每一个网络接口绑定的所有ip
                Enumeration address = networks.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (address.hasMoreElements()) {
                    InetAddress ip = (InetAddress) address.nextElement();
                    if (!ip.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(ip.getHostAddress())) {
                        ipaddress = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            Log.e("", "获取本地ip地址失败");
            e.printStackTrace();
        }
        Log.d(TAG, "本机IP:" + ipaddress);
        return ipaddress;
    }
}
